<script>
  const treeData = [
    {
      id: "p1",
      title: '广东',
      children: [{
        id: "p1-1",
        title: '广州',
      }]
    },
    {
      id: "p2",
      title: "四川",
      children: [{
        id: "p2-1",
        title: "成都",
        children: [{
          id: "p2-1-1",
          title: "高新区",
        }]
      },
      {
        id: "p2-2",
        title: "德阳"
      },
      {
        id: "p2-3",
        title: "绵阳"
      }]
    }
  ]

  Array.prototype.treeToList = function (children = 'children', pid, id) {
    const list = []
    const queue = [...this]
    if(pid) {
      if(!id) {
        id = 'id'
      }
      for (const node of queue) {
        node[pid] = 0
      }
    }
    
    while (queue.length) {
      const node = queue.shift()
      
      node[pid]
      const childrenData = node[children]

      if (childrenData) {
        if(pid) {
          for (const no of childrenData) {
            no[pid] = node[id]
          }
        }
        queue.push(...childrenData)
      }
      list.push(node)
    }
    return list
  }

  Array.prototype.listToTree = function (pid = 'pid', id = 'id', children = 'children') {
    const tree = []
    for (const node of this) {
      // pid 空 或 0 为根节点
      if (!node[pid] || node[pid] === 0) {
        let p = { ...node }
        p[children] = getChildren(p[id], this)
        tree.push(p)
      }
    }
    function getChildren(id, list) {
      const children = []
      for (const node of list) {
        if (node[pid] === id) {
          children.push(node)
        }
      }

      for (const node of children) {
        const children = getChildren(node[id], list)
        if (children.length) {
          node[children] = children
        }
      }
      return children
    }

    return tree
  }

  // Array.prototype.filterTree = function (, children = 'children') {
  //   const filterChildrenTree = (resTree, treeItem) => {
  //     if (treeItem.title.includes(key)) {
  //       resTree.push(treeItem)
  //       return resTree
  //     }
  //     if (Array.isArray(treeItem.children)) {
  //       const children = treeItem.children.reduce(filterChildrenTree, []);

  //       const data = { ...treeItem, children }

  //       if (children.length) {
  //         resTree.push({ ...data })
  //       }
  //     }
  //     return resTree;
  //   };
  //   return tree.reduce(filterChildrenTree, []);
  // }

  // Array.prototype.treeToList2 = function (children = 'children') {
  //   const list = []
  //   const stack = [...this]
  //   while (stack.length) {
  //     const node = stack.pop()
  //     const childrenData = node[children]
  //     if (childrenData) {
  //       stack.push(...childrenData)
  //     }
  //     list.push(node)
  //   }
  //   return list
  // }

  // console.log('list', treeData.treeToList('children', 'pid'))
  console.log('list', treeData.treeToList('children', 'pid').listToTree())





</script>